package com.shao.commons.utils;

import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class CodeUtils {

    private static Map<String, Val> codesMap = new ConcurrentHashMap<>(16);

    /**
     * 获取验证码
     * @param username 用户名
     * @return  返回
     */
    public static Integer getCode(String username) {
        Val<Integer> val = codesMap.get(username);
        if (System.currentTimeMillis() > val.getExpirationTime()) {
            clearCode(username);
            return null;
        }
        return val.data;
    }

    /**
     * 存储验证码
     * @param username
     * @param code
     * @param expirationTime
     * @param timeUnit
     */
    public static void setCode(String username, Integer code, int expirationTime, TimeUnit timeUnit) {
        Val val = new Val<>()
                .setData(code)
                .setExpirationTime(System.currentTimeMillis() + timeUnit.toMillis(expirationTime));
        codesMap.put(username, val);
    }

    /**
     * 清除已使用或者过期的的验证码
     * @param username
     */
    public static void clearCode(String username) {
        codesMap.remove(username);
    }

    @Data
    @Accessors(chain = true)
    private static class Val<T> {
        private T data;
        private Long expirationTime;
    }
}
